package com.easylinkin.linkappapi.webcammanage.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easylinkin.linkappapi.common.utils.DateUtil;
import com.easylinkin.linkappapi.common.utils.excel.ExcelConstant;
import com.easylinkin.linkappapi.common.utils.excel.ExcelTools;
import com.easylinkin.linkappapi.common.utils.io.OutputStreamUtil;
import com.easylinkin.linkappapi.elasticsearch.entity.*;
import com.easylinkin.linkappapi.security.context.LinkappUserContextProducer;
import com.easylinkin.linkappapi.security.entity.LinkappUser;
import com.easylinkin.linkappapi.webcammanage.entity.DataAnalystBean;
import com.easylinkin.linkappapi.webcammanage.entity.DataExcelModel;
import com.easylinkin.linkappapi.webcammanage.entity.DataStaticticsBean;
import com.easylinkin.linkappapi.webcammanage.entity.QueryHistogramBean;
import com.easylinkin.linkappapi.webcammanage.mapper.DataAnalystMapper;
import com.easylinkin.linkappapi.webcammanage.service.DataStatisticsService;
import com.easylinkin.linkappapi.webcammanage.util.YYSHDateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.script.Script;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation;
import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramInterval;
import org.elasticsearch.search.aggregations.bucket.range.RangeAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.sum.ParsedSum;
import org.elasticsearch.search.aggregations.metrics.sum.Sum;
import org.elasticsearch.search.aggregations.metrics.sum.SumAggregationBuilder;
import org.elasticsearch.search.aggregations.pipeline.ParsedSimpleValue;
import org.elasticsearch.search.aggregations.pipeline.bucketmetrics.avg.AvgBucketPipelineAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.*;

@Service
@Slf4j
public class DataStatisticsServiceImpl extends ServiceImpl<DataAnalystMapper, DataAnalystBean> implements DataStatisticsService {

    private ESconfig eSconfig;

//    private final static String indexStrES = "testlqh";//dev
    private final static String indexStrES = "yysh";//test
    private final static String dataAnalystES = "data_analyst";

    @Autowired
    public void setESconfig(ESconfig eSconfig) {
        this.eSconfig = eSconfig;
    }

    @Resource
    private LinkappUserContextProducer linkappUserContextProducer;

    @Override
    public DataStaticticsBean momData() {
        RestHighLevelClient rhlClient = eSconfig.getFactory().getRhlClient();
        DataStaticticsBean dsb = new DataStaticticsBean();

        analysisTotalDataStatistic(dsb);//总排泥、加药、进药数量统计
        analysisAvgDataStatistic(dsb);//统计总排泥、加药、进药日均值
        analysisDayMom(dsb); //统计总排泥、加药、进药日环比
        analysisWeekMom(dsb);//统计总排泥、加药、进药周环比

        return dsb;
    }

    @Override
    public EsHistogramResponseModel histogram(QueryHistogramBean queryHistogramBean) {
        Assert.notNull(queryHistogramBean.getDataType(), "查看数据类型 不能为空, 请选择排泥,加药,进药量");
        if(StringUtils.isEmpty(queryHistogramBean.getStartTime()) || StringUtils.isEmpty(queryHistogramBean.getEndTime())){

            Assert.notNull(queryHistogramBean.getTimeType(), "查看时间类型 不能为空, 请选择本周,本月,全年");
        }
        // ES聚合数据
        EsHistogramResponseModel histogramDataByCondition = getHistogramDataByCondition(queryHistogramBean);

        return histogramDataByCondition;
    }

    @Override
    public void exportHistogram(QueryHistogramBean queryHistogramBean, HttpServletRequest request, HttpServletResponse response) {
        // 根据条件获取数据，封装Excel数据
        StringBuilder titleAdaptor = new StringBuilder();

        //  集合<T> 必须定义类型
        List<DataExcelModel> result = new ArrayList<DataExcelModel>();
        EsHistogramResponseModel histogram = histogram(queryHistogramBean);
        Map<String, Double> resultMap = null;
        if(queryHistogramBean.getTimeType().equals(1)){
            titleAdaptor.append("本周");
            resultMap = histogram.getCommonMap();
        }else if(queryHistogramBean.getTimeType().equals(2)){
            titleAdaptor.append("本月");
            resultMap = histogram.getCommonMap();
        }else if(queryHistogramBean.getTimeType().equals(3)){
            titleAdaptor.append("全年");
            resultMap = histogram.getCommonMap();
        }else if(queryHistogramBean.getTimeType().equals(4)){
            titleAdaptor.append("");
            resultMap = histogram.getCommonMap();
        }
        if(resultMap == null){
            log.info("无数据, 该范围内无数据");
            return ;
        }
        Double totalCount = 0.0;
        for(Map.Entry<String, Double> entry :resultMap.entrySet()){
            DataExcelModel dem = new DataExcelModel();
            dem.setDateKey(entry.getKey());
            dem.setDateValue(entry.getValue());
            totalCount += entry.getValue();
            result.add(dem);
        }

        //  表头
        String keyValue = "时间:dateKey,总量:dateValue";

        //  根据查询条件动态获取title名称
        if(queryHistogramBean.getDataType().equals(1)){
            titleAdaptor.append("排泥量");
        }else if(queryHistogramBean.getDataType().equals(2)){
            titleAdaptor.append("加药量");
        }else if(queryHistogramBean.getDataType().equals(3)){
            titleAdaptor.append("进药量");
        }

        //  标题下的小标信息，可做统计数据展示
        List<String> stringList = new ArrayList<String>();
        stringList.add("统计总量");
        stringList.add(new BigDecimal(totalCount).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() + "m³");

        String title = "岳阳石化" + titleAdaptor.toString() + "统计数据";

        String fileName = title + ".xls";
        try {
            OutputStream outputStream = OutputStreamUtil
                    .getOutputStream(request, response, fileName);
            ExcelTools.exportBankExcel(outputStream, keyValue, result, ExcelConstant.XLS, title, stringList);
            response.flushBuffer();
            outputStream.close();
        } catch (IOException e) {
            log.error("excel导出失败");
            throw new RuntimeException("excel导出失败！IOException异常" + e.getMessage());
        } catch (Exception e) {
            log.error("excel导出失败");
            throw new RuntimeException("excel导出失败！" + e.getMessage());
        }
    }

    public EsHistogramResponseModel getHistogramDataByCondition(QueryHistogramBean queryHistogramBean){
        EsHistogramResponseModel ehrm = new EsHistogramResponseModel();
        //
        RestHighLevelClient rhlClient = eSconfig.getFactory().getRhlClient();
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        SumAggregationBuilder statisticsData = null;
        String sumValueResult = "";
        String fieldValue = "";
        if(queryHistogramBean.getDataType() != null && queryHistogramBean.getDataType().equals(1)){//排泥量
            sumValueResult = "day_paini_num";
            fieldValue = "painiNum";
        }
        else if(queryHistogramBean.getDataType() != null && queryHistogramBean.getDataType().equals(2)){//加药量
            sumValueResult = "day_jiayao_num";
            fieldValue = "jiayaoNum";
        }
        else if(queryHistogramBean.getDataType() != null && queryHistogramBean.getDataType().equals(3)){//进药量
            sumValueResult = "day_jinyao_num";
            fieldValue = "jinyaoNum";
        }
        statisticsData = AggregationBuilders.sum(sumValueResult).field(fieldValue);
        LinkappUser currentUser = linkappUserContextProducer.getCurrent();
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        MatchQueryBuilder tenantIdQuery = QueryBuilders.matchQuery("tenantId", currentUser.getTenantId());
        boolQueryBuilder.must(tenantIdQuery);

        if(queryHistogramBean.getTimeType() != null && queryHistogramBean.getTimeType().equals(1)){//本周
            Date[] currentWeekStartAndEndDate = YYSHDateUtil.getCurrentWeekStartAndEndDate();
            String startMonday = null;
            String endSunday = null;
            startMonday = DateUtil.format(currentWeekStartAndEndDate[0], DateUtil.DATE_TIME_FORMAT_DAY);//本周第一天
            endSunday = DateUtil.format(currentWeekStartAndEndDate[1], DateUtil.DATE_TIME_FORMAT_DAY);//本周最后一天
            /*if(StringUtils.isEmpty(queryHistogramBean.getStartTime())){
               startMonday = DateUtil.format(currentWeekStartAndEndDate[0], DateUtil.DATE_TIME_FORMAT_DAY);//本周第一天
            }else {
                startMonday = queryHistogramBean.getStartTime();
            }
            if(StringUtils.isEmpty(queryHistogramBean.getEndTime())){
                endSunday = DateUtil.format(currentWeekStartAndEndDate[1], DateUtil.DATE_TIME_FORMAT_DAY);//本周最后一天
            }else {
                endSunday = queryHistogramBean.getEndTime();
            }*/
            QueryBuilder rangeQuery = QueryBuilders.rangeQuery("createTime").gte(startMonday + " 00:00:00").lt(endSunday + " 23:59:59");

            RangeAggregationBuilder createTimeRanges = AggregationBuilders.range("create_time_ranges")
                    .script(new Script("doc['createTime'].value.getDayOfWeek()"))
                    .keyed(true)
                    .addRange("1", 1, 2)
                    .addRange("2", 2, 3)
                    .addRange("3", 3, 4)
                    .addRange("4", 4, 5)
                    .addRange("5", 5, 6)
                    .addRange("6", 6, 7)
                    .addUnboundedFrom("7", 7);
            boolQueryBuilder.must(rangeQuery);
            searchSourceBuilder.query(boolQueryBuilder).aggregation(createTimeRanges.subAggregation(statisticsData));
        }
        else if(queryHistogramBean.getTimeType() != null && queryHistogramBean.getTimeType().equals(2)){//本月
            String firstDayOfMonth = null;
            String currentDayOfMonth = null;
            firstDayOfMonth = YYSHDateUtil.getFirstDayOfMonth();//本月第一天
            currentDayOfMonth = DateUtil.format(new Date(), DateUtil.DATE_TIME_FORMAT_DAY);//当前日期
            /*if(StringUtils.isEmpty(queryHistogramBean.getStartTime())){
                firstDayOfMonth = YYSHDateUtil.getFirstDayOfMonth();//本月第一天
            }else {
                firstDayOfMonth = queryHistogramBean.getStartTime();
            }
            if(StringUtils.isEmpty(queryHistogramBean.getEndTime())){
                currentDayOfMonth = DateUtil.format(new Date(), DateUtil.DATE_TIME_FORMAT_DAY);//当前日期
            }else {
                currentDayOfMonth = queryHistogramBean.getEndTime();
            }*/
            QueryBuilder rangeQuery = QueryBuilders.rangeQuery("createTime").gte(firstDayOfMonth + " 00:00:00").lt(currentDayOfMonth + " 23:59:59");
            DateHistogramAggregationBuilder dhab = AggregationBuilders.dateHistogram("groupCreateTime").field("createTime").format("yyyy-MM-dd").dateHistogramInterval(DateHistogramInterval.DAY);
            boolQueryBuilder.must(rangeQuery);
            searchSourceBuilder.query(boolQueryBuilder).sort("createTime", SortOrder.ASC).aggregation(dhab.subAggregation(statisticsData));
        }
        else if(queryHistogramBean.getTimeType() != null && queryHistogramBean.getTimeType().equals(3)){//全年
            String firstDayOfYear = null;
            String currentDayOfYear = null;
            firstDayOfYear = DateUtil.getYear(new Date()) + "-01-01";//今年第一天
            currentDayOfYear = DateUtil.format(new Date(), DateUtil.DATE_TIME_FORMAT_DAY);//当前日期
            /*if(StringUtils.isEmpty(queryHistogramBean.getStartTime())){
                firstDayOfYear = DateUtil.getYear(new Date()) + "-01-01";//今年第一天
            }else {
                firstDayOfYear = queryHistogramBean.getStartTime();
            }
            if(StringUtils.isEmpty(queryHistogramBean.getEndTime())){
                currentDayOfYear = DateUtil.format(new Date(), DateUtil.DATE_TIME_FORMAT_DAY);//当前日期
            }else {
                currentDayOfYear = queryHistogramBean.getEndTime();
            }*/
            QueryBuilder rangeQuery = QueryBuilders.rangeQuery("createTime").gte(firstDayOfYear + " 00:00:00").lt(currentDayOfYear + " 23:59:59");

            boolQueryBuilder.must(rangeQuery);
            DateHistogramAggregationBuilder dhab = AggregationBuilders.dateHistogram("groupCreateTime").field("createTime").format("yyyy-MM").dateHistogramInterval(DateHistogramInterval.MONTH);

            searchSourceBuilder.query(boolQueryBuilder).sort("createTime", SortOrder.ASC).aggregation(dhab.subAggregation(statisticsData));
        }
        else if(!StringUtils.isEmpty(queryHistogramBean.getStartTime()) && !StringUtils.isEmpty(queryHistogramBean.getEndTime())){
            Long dateInteval = YYSHDateUtil.getDateInteval(queryHistogramBean.getStartTime(), queryHistogramBean.getEndTime(), DateUtil.DATE_TIME_FORMAT_DAY);
            String startMonday = queryHistogramBean.getStartTime();
            String endSunday = queryHistogramBean.getEndTime();

            QueryBuilder rangeQuery = QueryBuilders.rangeQuery("createTime").gte(startMonday).lt(endSunday);
//            QueryBuilder rangeQuery = QueryBuilders.rangeQuery("createTime").gte(startMonday + " 00:00:00").lt(endSunday + " 23:59:59");
            DateHistogramAggregationBuilder dhab = null;
            if(dateInteval > 31*24){//根据月分组
                dhab = AggregationBuilders.dateHistogram("groupCreateTime").field("createTime").format("yyyy-MM").dateHistogramInterval(DateHistogramInterval.MONTH);
            }else {//根据每天分组
                dhab = AggregationBuilders.dateHistogram("groupCreateTime").field("createTime").format("yyyy-MM-dd").dateHistogramInterval(DateHistogramInterval.DAY);
            }
            boolQueryBuilder.must(rangeQuery);
            searchSourceBuilder.query(boolQueryBuilder).sort("createTime", SortOrder.ASC).aggregation(dhab.subAggregation(statisticsData));
        }else {
            return null;
        }

        SearchResponse searchResponse = startRequestToES(indexStrES, dataAnalystES, searchSourceBuilder);
        if(searchResponse == null){
            return null;
        }
        //  解析searchResponse结果
        Map<String, Double> commonMap = new LinkedHashMap<String, Double>();
        if(queryHistogramBean.getTimeType() != null && queryHistogramBean.getTimeType().equals(1)){//本周统计数据解析
            Aggregation create_time_ranges = searchResponse.getAggregations().get("create_time_ranges");
            MultiBucketsAggregation histo = (MultiBucketsAggregation) create_time_ranges;
            List<? extends MultiBucketsAggregation.Bucket> buckets = histo.getBuckets();

            for (MultiBucketsAggregation.Bucket bucket : buckets) {
                ParsedSum parsedSum = (ParsedSum) bucket.getAggregations().get(sumValueResult);
                log.info("key=" + bucket.getKey()+", count="+ bucket.getDocCount() + ", value=" + parsedSum.getValue());
                /*if(parsedSum.getValue() > 0){//暂时在代码中过滤doc_count=0的记录
                    commonMap.put(bucket.getKey().toString(), parsedSum.getValue());
                }*/

                commonMap.put(bucket.getKey().toString(), new BigDecimal(parsedSum.getValue()).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
            }
            Date[] currentWeekStartAndEndDate = YYSHDateUtil.getCurrentWeekStartAndEndDate();
            String startMonday = DateUtil.format(currentWeekStartAndEndDate[0], DateUtil.DATE_TIME_FORMAT_DAY);//本周第一天
            String endSunday = DateUtil.format(currentWeekStartAndEndDate[1], DateUtil.DATE_TIME_FORMAT_DAY);//本周最后一天
            ehrm.setCommonMap(addDate(commonMap, 1, startMonday, endSunday));
//            ehrm.setCommonMap(commonMap);
        }
        else if(queryHistogramBean.getTimeType() != null && queryHistogramBean.getTimeType().equals(2)){//本月统计数据解析
            Aggregation create_time_ranges = searchResponse.getAggregations().get("groupCreateTime");
            MultiBucketsAggregation histo = (MultiBucketsAggregation) create_time_ranges;
            List<? extends MultiBucketsAggregation.Bucket> buckets = histo.getBuckets();

            for (MultiBucketsAggregation.Bucket bucket : buckets) {
                ParsedSum parsedSum = (ParsedSum) bucket.getAggregations().get(sumValueResult);
                log.info("key=" + bucket.getKeyAsString()+", count="+ bucket.getDocCount() + ", value=" + parsedSum.getValue());
                if(parsedSum.getValue() > 0){//暂时在代码中过滤doc_count=0的记录
                    commonMap.put(bucket.getKeyAsString().toString(), new BigDecimal(parsedSum.getValue()).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                }
            }
            ehrm.setCommonMap(addDate(commonMap, 2, null, null));
        }
        else if(queryHistogramBean.getTimeType() != null && queryHistogramBean.getTimeType().equals(3)){//全年统计数据解析
            Aggregation create_time_ranges = searchResponse.getAggregations().get("groupCreateTime");
            MultiBucketsAggregation histo = (MultiBucketsAggregation) create_time_ranges;
            List<? extends MultiBucketsAggregation.Bucket> buckets = histo.getBuckets();

            for (MultiBucketsAggregation.Bucket bucket : buckets) {
                ParsedSum parsedSum = (ParsedSum) bucket.getAggregations().get(sumValueResult);
                log.info("key=" + bucket.getKeyAsString()+", count="+ bucket.getDocCount() + ", value=" + parsedSum.getValue());
                if(parsedSum.getValue() > 0){//暂时在代码中过滤doc_count=0的记录
                    commonMap.put(bucket.getKeyAsString().toString(), new BigDecimal(parsedSum.getValue()).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                }
            }
            ehrm.setCommonMap(addDate(commonMap, 3, null, null));
        }else if(!StringUtils.isEmpty(queryHistogramBean.getStartTime()) && !StringUtils.isEmpty(queryHistogramBean.getEndTime())){
            Aggregation create_time_ranges = searchResponse.getAggregations().get("groupCreateTime");
            MultiBucketsAggregation histo = (MultiBucketsAggregation) create_time_ranges;
            List<? extends MultiBucketsAggregation.Bucket> buckets = histo.getBuckets();

            for (MultiBucketsAggregation.Bucket bucket : buckets) {
                ParsedSum parsedSum = (ParsedSum) bucket.getAggregations().get(sumValueResult);
                log.info("key=" + bucket.getKeyAsString()+", count="+ bucket.getDocCount() + ", value=" + parsedSum.getValue());
                if(parsedSum.getValue() > 0){//暂时在代码中过滤doc_count=0的记录
                    commonMap.put(bucket.getKeyAsString().toString(), new BigDecimal(parsedSum.getValue()).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                }
            }
            Long dateInteval = YYSHDateUtil.getDateInteval(queryHistogramBean.getStartTime(), queryHistogramBean.getEndTime(), DateUtil.DATE_TIME_FORMAT_DAY);
            if(dateInteval > 31*24){//根据月分组
                ehrm.setCommonMap(addDate(commonMap, 5, queryHistogramBean.getStartTime(), queryHistogramBean.getEndTime()));
                ehrm.setDayOrMonth("月");
            }else {//根据每天分组
                ehrm.setCommonMap(addDate(commonMap, 4, queryHistogramBean.getStartTime(), queryHistogramBean.getEndTime()));
                ehrm.setDayOrMonth("日");
            }
        }
        return ehrm;
    }

    private Map<String, Double> addDate(Map<String, Double> commonMap, int type, String startTime, String endTime){
        Map<String, Double> commonMapResult = new LinkedHashMap<String, Double>();
        if(type == 1){
            // 替换周为日期
            List<String> dayByMonth = YYSHDateUtil.getDays(startTime, endTime);
            for (int i = 0 ; i < dayByMonth.size(); i++) {
                String resultDate = dayByMonth.get(i).substring(5, 10);
                commonMapResult.put(resultDate, commonMap.get(i+1 + ""));
            }
        }
        else if(type == 2){
            // 补齐一月内的每一天
            List<String> dayByMonth = YYSHDateUtil.getDayByMonth(Integer.valueOf(DateUtil.getCurrentYear()), DateUtil.getMonthOfYear(new Date()) - 1);
            for (String dayStr:
                    dayByMonth) {
                if(commonMap.containsKey(dayStr)){
                    commonMapResult.put(dayStr, commonMap.get(dayStr));
                }else {
                    commonMapResult.put(dayStr, 0.00);
                }
            }

        }else if(type == 3){
            // 补齐一年内的每一月
            List<String> monthByYear = YYSHDateUtil.getMonthByYear(DateUtil.getCurrentYear());
            for (String monthStr:
                monthByYear) {
                if(commonMap.containsKey(monthStr)){
                    commonMapResult.put(monthStr, commonMap.get(monthStr));
                }else {
                    commonMapResult.put(monthStr, 0.00);
                }
            }
        }else if(type == 4){//根据区间按照日显示
            // 补齐区间内的每一天
            List<String> dayByMonth = YYSHDateUtil.getDays(startTime, endTime);
            for (String dayStr:
                    dayByMonth) {
                if(commonMap.containsKey(dayStr)){
                    commonMapResult.put(dayStr, commonMap.get(dayStr));
                }else {
                    commonMapResult.put(dayStr, 0.00);
                }
            }
        }else if(type == 5){//根据区间按照月显示
            List<String> monthByYear = YYSHDateUtil.getMonths(startTime, endTime);
            for (String monthStr:
                    monthByYear) {
                if(commonMap.containsKey(monthStr)){
                    commonMapResult.put(monthStr, commonMap.get(monthStr));
                }else {
                    commonMapResult.put(monthStr, 0.00);
                }
            }
        }
        return commonMapResult;
    }


    //总量统计
    public void analysisTotalDataStatistic(DataStaticticsBean dataAnalyst) {
        RestHighLevelClient rhlClient = eSconfig.getFactory().getRhlClient();
        //总排泥、加药、进药数量统计
        SumAggregationBuilder paini_num = AggregationBuilders.sum("totalPainiNum").field("painiNum");
        SumAggregationBuilder jiayao_num = AggregationBuilders.sum("totalJiayaoNum").field("jiayaoNum");
        SumAggregationBuilder jinyao_num = AggregationBuilders.sum("totalJinyaoNum").field("jinyaoNum");
        LinkappUser currentUser = linkappUserContextProducer.getCurrent();
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        MatchQueryBuilder tenantIdQuery = QueryBuilders.matchQuery("tenantId", currentUser.getTenantId());
        boolQueryBuilder.must(tenantIdQuery);

        QueryBuilder rangeQuery = QueryBuilders.rangeQuery("createTime").gte(DateUtil.getCurrentYear() + "-01-01 00:00:00");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        boolQueryBuilder.must(rangeQuery);
        searchSourceBuilder.query(boolQueryBuilder).aggregation(paini_num).aggregation(jiayao_num).aggregation(jinyao_num);

        SearchResponse searchResponse = startRequestToES(indexStrES, dataAnalystES, searchSourceBuilder);
        if(searchResponse == null){
            log.info("ES查询结果返回的对象为空！！！！");
            return ;
        }
        Sum stpn = searchResponse.getAggregations().get("totalPainiNum");
        Sum stjin = searchResponse.getAggregations().get("totalJinyaoNum");
        Sum stjia = searchResponse.getAggregations().get("totalJiayaoNum");

        dataAnalyst.setTotalPainiNum(new BigDecimal(stpn.getValue()).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
        dataAnalyst.setTotalJiayaoNum(new BigDecimal(stjia.getValue()).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
        dataAnalyst.setTotalJinyaoNum(new BigDecimal(stjin.getValue()).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
    }

    //日均统计
    public void analysisAvgDataStatistic(DataStaticticsBean dataAnalyst) {
        RestHighLevelClient rhlClient = eSconfig.getFactory().getRhlClient();
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        LinkappUser currentUser = linkappUserContextProducer.getCurrent();
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        MatchQueryBuilder tenantIdQuery = QueryBuilders.matchQuery("tenantId", currentUser.getTenantId());
        boolQueryBuilder.must(tenantIdQuery);
        QueryBuilder rangeQuery = QueryBuilders.rangeQuery("createTime").gte(DateUtil.getCurrentYear() + "-01-01 00:00:00");
        boolQueryBuilder.must(rangeQuery);
        DateHistogramAggregationBuilder dhab = AggregationBuilders.dateHistogram("groupCreateTime").field("createTime").format("yyyy-MM-dd").dateHistogramInterval(DateHistogramInterval.DAY);
        SumAggregationBuilder day_paini_num = AggregationBuilders.sum("day_paini_num").field("painiNum");
        SumAggregationBuilder day_jiayao_num = AggregationBuilders.sum("day_jiayao_num").field("jiayaoNum");
        SumAggregationBuilder day_jinyao_num = AggregationBuilders.sum("day_jinyao_num").field("jinyaoNum");
        dhab.subAggregation(day_paini_num).subAggregation(day_jiayao_num).subAggregation(day_jinyao_num);
        AvgBucketPipelineAggregationBuilder paini_avg = new AvgBucketPipelineAggregationBuilder("paini_avg", "groupCreateTime>day_paini_num");
        AvgBucketPipelineAggregationBuilder jiayao_avg = new AvgBucketPipelineAggregationBuilder("jiayao_avg", "groupCreateTime>day_jiayao_num");
        AvgBucketPipelineAggregationBuilder jinyao_avg = new AvgBucketPipelineAggregationBuilder("jinyao_avg", "groupCreateTime>day_jinyao_num");

        searchSourceBuilder.query(boolQueryBuilder).aggregation(dhab).aggregation(paini_avg).aggregation(jiayao_avg).aggregation(jinyao_avg);

        SearchResponse searchResponse = startRequestToES(indexStrES, dataAnalystES, searchSourceBuilder);
        if(searchResponse == null){
            log.info("ES查询结果返回的对象为空！！！！");
            return ;
        }
        Map<String, Aggregation> map = searchResponse.getAggregations().getAsMap();
        double apn = ((ParsedSimpleValue)map.get("paini_avg")).value();
        double ajia = ((ParsedSimpleValue)map.get("jiayao_avg")).value();
        double ajin = ((ParsedSimpleValue)map.get("jinyao_avg")).value();

        dataAnalyst.setPainiDayAvg(new BigDecimal(apn).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
        dataAnalyst.setJiayaoDayAvg(new BigDecimal(ajia).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
        dataAnalyst.setJinyaoDayAvg(new BigDecimal(ajin).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
    }

    // 统计日环比
    public void analysisDayMom(DataStaticticsBean dataAnalyst) {
        RestHighLevelClient rhlClient = eSconfig.getFactory().getRhlClient();
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        LinkappUser currentUser = linkappUserContextProducer.getCurrent();
        MatchQueryBuilder tenantIdQuery = QueryBuilders.matchQuery("tenantId", currentUser.getTenantId());

        BoolQueryBuilder boolQueryBuilder1 = QueryBuilders.boolQuery();
        boolQueryBuilder1.must(tenantIdQuery);
        //获取昨天日期
        Date yDate = DateUtil.addDay(new Date(), -1);
        String yesterday = DateUtil.format(yDate, DateUtil.DATE_TIME_FORMAT_DAY);
        QueryBuilder boolQuery = QueryBuilders.termQuery("createTime",yesterday);
        boolQueryBuilder1.must(boolQuery);
        SumAggregationBuilder paini_num = AggregationBuilders.sum("day_paini_num").field("painiNum");
        SumAggregationBuilder jiayao_num = AggregationBuilders.sum("day_jiayao_num").field("jiayaoNum");
        SumAggregationBuilder jinyao_num = AggregationBuilders.sum("day_jinyao_num").field("jinyaoNum");
        searchSourceBuilder.query(boolQueryBuilder1).aggregation(paini_num).aggregation(jiayao_num).aggregation(jinyao_num);

        SearchResponse ySearchResponse = startRequestToES(indexStrES, dataAnalystES, searchSourceBuilder);
        if(ySearchResponse == null){
            log.info("ES查询结果返回的对象为空！！！！");
            return ;
        }
        Sum sypn = ySearchResponse.getAggregations().get("day_paini_num");
        Sum syjin = ySearchResponse.getAggregations().get("day_jinyao_num");
        Sum syjia = ySearchResponse.getAggregations().get("day_jiayao_num");
        log.info("上次日总排泥量=" + sypn.getValue() + "上次日总进药量=" + syjin.getValue() + "上次日总加药量=" + syjia.getValue());
        //获取前天日期
        Date bDate = DateUtil.addDay(new Date(), -2);
        String beforeDay = DateUtil.format(bDate, DateUtil.DATE_TIME_FORMAT_DAY);
        SearchSourceBuilder bSearchSourceBuilder = new SearchSourceBuilder();
        QueryBuilder boolQuery2 = QueryBuilders.termQuery("createTime",beforeDay);
        BoolQueryBuilder boolQueryBuilder2 = QueryBuilders.boolQuery();
        boolQueryBuilder2.must(tenantIdQuery);
        boolQueryBuilder2.must(boolQuery2);
        bSearchSourceBuilder.query(boolQueryBuilder2).aggregation(paini_num).aggregation(jiayao_num).aggregation(jinyao_num);

        SearchResponse bSearchResponse = startRequestToES(indexStrES, dataAnalystES, bSearchSourceBuilder);
        if(bSearchResponse == null){
            log.info("ES查询结果返回的对象为空！！！！");
            return ;
        }
        Sum sbpn = bSearchResponse.getAggregations().get("day_paini_num");
        Sum sbjin = bSearchResponse.getAggregations().get("day_jinyao_num");
        Sum sbjia = bSearchResponse.getAggregations().get("day_jiayao_num");
        log.info("上上次(前次)日总排泥量=" + sbpn.getValue() + "前次日总进药量=" + sbjin.getValue() + "前次日总加药量=" + sbjia.getValue());
        Double pndResult = 1.0;
        if(sbpn.getValue() != 0.0){
            pndResult = (Double.valueOf(sypn.getValue()) - Double.valueOf(sbpn.getValue()))/Double.valueOf(sbpn.getValue());
        }
        dataAnalyst.setMomStatisticPainiDay(new BigDecimal(pndResult).multiply(BigDecimal.valueOf(100L)).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());

        Double jindResult = 1.0;
        if(sbjin.getValue() != 0.0){
            jindResult= (Double.valueOf(syjin.getValue()) - Double.valueOf(sbjin.getValue()))/Double.valueOf(sbjin.getValue());
        }
        dataAnalyst.setMomStatisticJinyaoDay(new BigDecimal(jindResult).multiply(BigDecimal.valueOf(100L)).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());

        Double jiadResult = 1.0;
        if(sbjia.getValue() != 0.0){
            jiadResult= (Double.valueOf(syjia.getValue()) - Double.valueOf(sbjia.getValue()))/Double.valueOf(sbjia.getValue());
        }
        dataAnalyst.setMomStatisticJiayaoDay(new BigDecimal(jiadResult).multiply(BigDecimal.valueOf(100L)).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());

    }

    // 统计周环比
    public void analysisWeekMom(DataStaticticsBean dataAnalyst) {
        RestHighLevelClient rhlClient = eSconfig.getFactory().getRhlClient();
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        LinkappUser currentUser = linkappUserContextProducer.getCurrent();
        MatchQueryBuilder tenantIdQuery = QueryBuilders.matchQuery("tenantId", currentUser.getTenantId());

        BoolQueryBuilder boolQueryBuilder1 = QueryBuilders.boolQuery();
        boolQueryBuilder1.must(tenantIdQuery);

        //获取当前周开始和结束日期
        Date[] currentWeekStartAndEndDate = YYSHDateUtil.getCurrentWeekStartAndEndDate();
        String startMonday = DateUtil.format(currentWeekStartAndEndDate[0], DateUtil.DATE_TIME_FORMAT_DAY);
        String currentDay = DateUtil.format(new Date(), DateUtil.DATE_TIME_FORMAT_DAY);
        QueryBuilder rangeQuery = QueryBuilders.rangeQuery("createTime").gte(startMonday + " 00:00:00").lt(currentDay + " 23:59:59");
        boolQueryBuilder1.must(rangeQuery);
        SumAggregationBuilder paini_num = AggregationBuilders.sum("week_paini_num").field("painiNum");
        SumAggregationBuilder jiayao_num = AggregationBuilders.sum("week_jiayao_num").field("jiayaoNum");
        SumAggregationBuilder jinyao_num = AggregationBuilders.sum("week_jinyao_num").field("jinyaoNum");
        searchSourceBuilder.query(boolQueryBuilder1).aggregation(paini_num).aggregation(jiayao_num).aggregation(jinyao_num);

        SearchResponse cSearchResponse = startRequestToES(indexStrES, dataAnalystES, searchSourceBuilder);
        if(cSearchResponse == null){
            log.info("ES查询结果返回的对象为空！！！！");
            return ;
        }
        Sum scpn = cSearchResponse.getAggregations().get("week_paini_num");
        Sum scjin = cSearchResponse.getAggregations().get("week_jinyao_num");
        Sum scjia = cSearchResponse.getAggregations().get("week_jiayao_num");
        log.info("上次周总排泥量=" + scpn.getValue() + "上次周总进药量=" + scjin.getValue() + "上次周总加药量=" + scjia.getValue());
        //获取上一周开始和结束日期
        Date[] beforeWeekStartAndEndDate = YYSHDateUtil.getBeforeWeekStartAndEndDate();
        String bMonday = DateUtil.format(beforeWeekStartAndEndDate[0], DateUtil.DATE_TIME_FORMAT_DAY);
        String bSunday = DateUtil.format(beforeWeekStartAndEndDate[1], DateUtil.DATE_TIME_FORMAT_DAY);
        SearchSourceBuilder bSearchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder2 = QueryBuilders.boolQuery();
        boolQueryBuilder2.must(tenantIdQuery);
        QueryBuilder rangeQuery2 = QueryBuilders.rangeQuery("createTime").gte(bMonday + " 00:00:00").lt(bSunday + " 23:59:59");
        boolQueryBuilder2.must(rangeQuery2);
        bSearchSourceBuilder.query(boolQueryBuilder2).aggregation(paini_num).aggregation(jiayao_num).aggregation(jinyao_num);

        SearchResponse bSearchResponse = startRequestToES(indexStrES, dataAnalystES, bSearchSourceBuilder);
        if(bSearchResponse == null){
            log.info("ES查询结果返回的对象为空！！！！");
            return ;
        }
        Sum sbpn = bSearchResponse.getAggregations().get("week_paini_num");
        Sum sbjin = bSearchResponse.getAggregations().get("week_jinyao_num");
        Sum sbjia = bSearchResponse.getAggregations().get("week_jiayao_num");
        log.info("上上次(前次)周总排泥量=" + sbpn.getValue() + "前次周总进药量=" + sbjin.getValue() + "前次周总加药量=" + sbjia.getValue());

        Double pndResult = 1.0;
        if(sbpn.getValue() != 0.0){
            pndResult= (Double.valueOf(scpn.getValue()) - Double.valueOf(sbpn.getValue()))/Double.valueOf(sbpn.getValue());
        }
        dataAnalyst.setMomStatisticPainiWeek(new BigDecimal(pndResult).multiply(BigDecimal.valueOf(100L)).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());

        Double jindResult = 1.0;
        if(sbjin.getValue() != 0.0){
            jindResult= (Double.valueOf(scjin.getValue()) - Double.valueOf(sbjin.getValue()))/Double.valueOf(sbjin.getValue());
        }
        dataAnalyst.setMomStatisticJinyaoWeek(new BigDecimal(jindResult).multiply(BigDecimal.valueOf(100L)).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());

        Double jiadResult = 1.0;
        if(sbjia.getValue() != 0.0){
            jiadResult= (Double.valueOf(scjia.getValue()) - Double.valueOf(sbjia.getValue()))/Double.valueOf(sbjia.getValue());
        }
        dataAnalyst.setMomStatisticJiayaoWeek(new BigDecimal(jiadResult).multiply(BigDecimal.valueOf(100L)).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());

    }

    //发起ES数据查询

    /**
     *
     * @param index 索引
     * @param type  类型
     * @param searchSourceBuilder   查询建造器
     * @return
     */
    public SearchResponse startRequestToES(String index, String type, SearchSourceBuilder searchSourceBuilder){
        log.info(searchSourceBuilder.aggregations().toString());
        RestHighLevelClient rhlClient = eSconfig.getFactory().getRhlClient();
        SearchRequest searchRequest = new SearchRequest(indexStrES).types(dataAnalystES).source(searchSourceBuilder);

        SearchResponse searchResponse = null;
        try {
            log.info("查询ES请求数据：" + searchRequest.toString());
            searchResponse = rhlClient.search(searchRequest, RequestOptions.DEFAULT);

        } catch (Exception e) {
            log.error("ES查询异常" + e.getMessage());
        }
        if (null == searchResponse) {
            log.info("ES查询结果返回的对象为空！！！！");
            return null;
        }
        return searchResponse;
    }

}
